import React, { Component } from 'react';

import {Menu, Icon, List, Layout} from 'antd';
import axios from 'axios';

import './index.css'

const SubMenu = Menu.SubMenu;
const MenuItemGroup = Menu.ItemGroup;

const {
  Header, Content, Footer, Sider,
} = Layout;

class Home extends Component {

  menus = new Map();
  state = {
    complete: false,
    list:[]
  };

  componentWillMount(){
    console.log('componentWillMount');
    let state = localStorage.getItem("state");
    let menus = localStorage.getItem("menus");
    if(state){
      this.state = JSON.parse(state);
      this.menus = this._jsonToMap(menus);
      this.state.menus = this.menus;
    }else {
      this.state.menus = new Map();
    }
    console.log(state);
  }
  componentDidMount(){
    if(this.state.menus.size > 0)return;
    let that = this;
    axios.get('https://gank.io/api/xiandu/categories')
      .then(resp => {
        console.log(resp);
        if(resp.status === 200){
          let data = resp.data;
          if(!data.error){
            let results = data.results;

            results.map(categorie => {
              axios.get('https://gank.io/api/xiandu/category/'+categorie.en_name)
                .then(resp => {
                  // TODO check data
                  let subCategorys = resp.data.results;

                  that.menus.set(categorie.name,subCategorys);
                  that.setState({
                    complete:true,
                    menus:that.menus
                  })
                  /*subCategorys.map(subCategory => {
                    /!*axios.get('https://gank.io/api/xiandu/data/id/'+subCategory.id+'/count/10/page/1')
                      .then(resp => {
                        let articles = resp.data.results;
                        articles.map(article => {
                          console.log(article.title);
                        })
                      })*!/

                    console.log(subCategory.id);
                  })*/
                })
            })
          }
        }

      })
  }

  handleClick(e, subitem) {
    //console.log('click ', subitem);

    axios.get('https://gank.io/api/xiandu/data/id/'+subitem.id+'/count/20/page/1')
      .then(resp => {
        let articles = resp.data.results;

        this.setState({
          list:articles
        })
        /*articles.map(article => {
          console.log(article.title);

        })*/
      })
  }

  handelArticle(e, article){
    //console.log(article);

    console.log(this.state);

    localStorage.setItem("state",JSON.stringify(this.state));
    localStorage.setItem("menus",this._mapToJson(this.state.menus));
    this.props.history.push({
      pathname:'/detail',
      state: article
    })
  }

  render() {
    var submenus = [];
    this.state.menus.forEach((key,menu) => {
      //console.log(key,menu);
      submenus.push( <SubMenu key={menu} title={menu}>
        {key.map(subitem => {
          return <Menu.Item key={subitem.id} onClick={(e) =>this.handleClick(e, subitem)}>{subitem.title}</Menu.Item>
        })}
      </SubMenu>)
    })

    let list = this.state.list;
    return (
      <div className="Home">

        <Layout>
          <Sider style={{
            overflow: 'auto', height: '100vh', position: 'fixed', left: 0,background:'#fff'
          }}>
            <Menu
              defaultSelectedKeys={['1']}
              defaultOpenKeys={['sub1']}
              mode="inline"
            >
              {submenus}
            </Menu>
          </Sider>
        </Layout>

        <Layout  style={{ marginLeft: 200 }}>
          <List
            size='large'
            bordered
            dataSource={list}
            renderItem={item => (<List.Item onClick={e => this.handelArticle(e,item)}>{item.title}</List.Item>)}
          />
        </Layout>
      </div>

    );
  }

  static _strMapToObj(strMap){
    let obj= Object.create(null);
    for (let[k,v] of strMap) {
      obj[k] = v;
    }
    return obj;
  }
  /**
   *map转换为json
   */
  _mapToJson(map) {
    return JSON.stringify(Home._strMapToObj(map));
  }

  static _objToStrMap(obj){
    let strMap = new Map();
    for (let k of Object.keys(obj)) {
      strMap.set(k,obj[k]);
    }
    return strMap;
  }
  /**
   *json转换为map
   */
  _jsonToMap(jsonStr){
    return Home._objToStrMap(JSON.parse(jsonStr));
  }

}

export default Home;